package com.bootdo.common.excel;

import com.alibaba.druid.util.StringUtils;
import com.bootdo.common.annotation.ExcelTileName;
import com.bootdo.common.utils.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * 
 * @author 郝江波
 *
 */
public class DachuExcelUtils <T>{
	 
	
	public void exportExcle(String fileName,Class clazz, List<T>  list,HttpServletResponse response) throws Exception {
			// 创建HSSFWorkbook对象(excel的文档对象)
			HSSFWorkbook wb = new HSSFWorkbook();
			// 建立新的sheet对象（excel的表单）
			HSSFSheet sheet = wb.createSheet(fileName);
			// 在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
			// 创建单元格（excel的单元格，参数为列索引，可以是0～255之间的任何一个
			/*	HSSFCell cell = row1.createCell(0);
			// 设置单元格内容
			cell.setCellValue("二维码地址");*/
			// 合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
			//sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));
			// 在sheet里创建第二行
			HSSFRow row2 = sheet.createRow(0);
			// 创建单元格并设置单元格内容
			
			Field [] fields = clazz.getDeclaredFields();
			if(null == fields || fields.length <= 0) {
				throw new NullPointerException("方法属性不能为空");
			}
			int i = 0;
			for(Field f : fields) {
				f.setAccessible(true);
				ExcelTileName excelTileName  = f.getAnnotation(ExcelTileName.class);
				if(null != excelTileName) {
					row2.createCell(i).setCellValue(excelTileName.value());
					i++;
				}				
			}
			i = 0;
			
			CellStyle  cellStyle = wb.createCellStyle();
			DataFormat format = wb.createDataFormat();			 
			cellStyle.setDataFormat(format.getFormat("0.00")); //设置数据格式	
			
			if(null != list && list.size() > 0) {
				for(int x = 0; x < list.size(); x++) {
					HSSFRow row = sheet.createRow((x+1));
					ObjectHander(list.get(x),row,cellStyle);
				}
			}
			
			// 输出Excel文件
			OutputStream output = response.getOutputStream();
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-disposition", "attachment; filename="+URLEncoder.encode(fileName+".xls","utf-8"));
			response.setContentType("application/msexcel");
			wb.write(output);	
			output.close();
	}
	
	
	public void ObjectHander(T t,HSSFRow row,CellStyle  cellStyle) throws IllegalArgumentException, IllegalAccessException {
		Field [] fields =  t.getClass().getDeclaredFields();
		if(null == fields || fields.length <= 0) {
			throw new NullPointerException("方法属性不能为空");
		}
		int i = 0;
		for(Field f : fields) {
			ExcelTileName excelTileName  = f.getAnnotation(ExcelTileName.class);
			if(null != excelTileName) {	 
				  f.setAccessible(true);
				  Object o = f.get(t);
				  if(null !=  o) {
					  if(o  instanceof Integer) {	
						  System.err.println(excelTileName.change());
						  if(StringUtils.isEmpty(excelTileName.change())) {
							  row.createCell(i).setCellValue((Integer) o);
						  }else {				
							  row.createCell(i).setCellValue( changeHander(excelTileName.change(), o));				  
						  }	  
					  } else
					  if(o  instanceof Long) {								 					 
						  if(StringUtils.isEmpty(excelTileName.change())) {
							  row.createCell(i).setCellValue((Long)  o );
						  }else {
							  row.createCell(i).setCellValue(changeHander(excelTileName.change(), o));				  
						  }	 
					  }else
					  if(o  instanceof Double) {
									
						  row.createCell(i).setCellStyle(cellStyle);
						  row.createCell(i).setCellValue((Double)  o);
					  }else
					  if(o  instanceof Date) {
						 /* CellStyle  cellStyle = wb.createCellStyle();
						  DataFormat format = wb.createDataFormat();
						  cellStyle.setDataFormat(format.getFormat("yyyy-MM-dd")); //设置数据格式
						  row.createCell(i).setCellType(HSSFCell.CELL_TYPE_NUMERIC);
						  row.createCell(i).setCellStyle(cellStyle);*/
						  row.createCell(i).setCellValue(DateUtils.format((Date)  o,"yyyy-MM-dd HH:mm:ss"));
					  }
					  else {
						  row.createCell(i).setCellValue(o.toString());
					  }
					
				  }else {
					  row.createCell(i).setCellValue("");
				  }
				 i++; 
			}
		}
		
	}
	
	String changeHander(String change,Object value) {
		
		String changeArray [] = change.split(",");
		if(null != changeArray && changeArray.length > 0) {
			for(int i = 0; i < changeArray.length; i++) {
				String[] kvArray = changeArray[i].split("=");
				String k = kvArray[0];
				String v = kvArray[1];			
				if(value.toString().equals(k)) {
					return v;
				}
			}
		}
		
		return "";
	}
	
}
